﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MvcMall.AdminWeb.Handlers;
using MvcMall.Core.Contacts.Services;
using MvcMall.Core.Contacts.Tasks;

namespace MvcMall.AdminWeb
{
    public partial class Login : BasePage
    {
        private IAdminUserTask _adminUserTask;
        private IIdentityService _identityService;

        protected void Page_Load(object sender, EventArgs e)
        {
            _adminUserTask = GetInstance<IAdminUserTask>();
            _identityService = GetInstance<IIdentityService>();

        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            var userName = txtUserName.Text.Trim().ToLower();
            var password = txtPaw.Text;
            var validateCode = txtCode.Text.Trim().ToLower();

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(validateCode))
            {
                ShowMsg("输入错误");
                return;
            }

            if (!ValidateCodeHandler.Check(validateCode))
            {
                ShowMsg("验证码不正确");
                return;
            }

            if (!_adminUserTask.ValidateUser(userName, password))
            {
                ShowMsg("用户名或密码不正确");
                return;
            }

            var user = _adminUserTask.GetUser(userName);
            if (user.IsLocked)
            {
                ShowMsg("对不起,您的账号已被锁定");
                return;
            }

            _identityService.SignIn(user.UserName, false);
            Response.Redirect("~/Manage/Index.aspx");
        }
    }
}